import React, { Component } from "react";
import { connect } from "react-redux";
import "./BankTransferMoney.scss";
import { ActionSheet, Toast, Modal, List, InputItem } from "antd-mobile";
import { setDialog } from "../../../Redux/Action/dialog/dialog";
import { checkTool } from "plugin-tool-check";
import Header from "../../../component/header/Header";
import BounceSpace from "../../../component/bottomInputBounceSpace/BounceSpace";
import yhTools from "../../../tools/yh";

const antnAlert = Modal.alert; //弹窗
//ActionSheet需要使用的内容-----开始-----
const isIPhone = new RegExp("\\biPhone\\b|\\biPod\\b", "i").test(
	window.navigator.userAgent
);
let wrapProps;
if (isIPhone) {
	wrapProps = {
		onTouchStart: e => e.preventDefault()
	};
}
//ActionSheet需要使用的内容-----结束-----
const data = [];

class BankTransferMoney extends Component {
	constructor(props) {
		super(props);
		this.state = {
			allMoney: 0, //凭证总金额
			onceToken: "", //防止上传凭证重复提交
			cardList: [
				{
					files: data,
					payAccount: "", //付款账号
					payAmt: "", //付款金额
					imageUrl: "" //上传图片地址
				}
			], //凭证数组
			isShowBounce: true, //该字段用于控制是否现在页面最底部的空白div，这样输入框才能被键盘顶上去
			keybordHeight: 3, //记录键盘的高度
			hasUpload: false //是否提交过
		};
	}

	componentDidMount() {
		this.setState({
			allMoney: this.props.repaymentMoney.totalLoanFee
				? this.props.repaymentMoney.totalLoanFee
				: "",
			onceToken: this.props.repaymentMoney.onceToken
				? this.props.repaymentMoney.onceToken
				: ""
		});
		let _that = this;
		setTimeout(() => {
			window.YHAuthorize.View.addEventListener("KeyboardEvent", res => {
				if (_that.state.keybordHeight == 3 && res.heightper != 0) {
					_that.setState({
						keybordHeight: res.heightper * window.innerHeight
					});
				}
			});
		}, 500);
	}

	render() {
		let headerParams = {
			phoneStyle: this.props.getAppPlatformsDatas.phoneX,
			goToback: true,
			leftPathName: "#/repaymentMoney",
			title: "银行转账"
		};
		return (
			<div
				className={
					this.props.getAppPlatformsDatas.phoneX
						? "bank-transfer-money-page mt168"
						: "bank-transfer-money-page mt128"
				}
			>
				<Header objParams={headerParams} />
				{/*<Header phoneStyle={this.props.getAppPlatformsDatas.phoneX} goback pathName="#/repaymentMoney" title='银行转账'/>*/}
				<div className="content-body" id="contentBody">
					<div className="top-div">
						<div className="top-money">
							<div className="money-tips">还款金额(元)</div>
							<div className="money-num">{this.state.allMoney}</div>
						</div>
						<div className="line-2"></div>
						<div className="tips">
							请将还款转账到以下用户，并提交转账凭证，最多支持上传3个凭证。
						</div>
						<div className="list1">
							<div className="item1">
								<label className="item-left1">银行账号</label>
								<label className="item-right1">114455744166</label>
							</div>
							<div className="item1">
								<label className="item-left1">账户名称</label>
								<label className="item-right1">重庆永辉小额贷款有限公司</label>
							</div>
							<div className="item1">
								<label className="item-left1">开户银行</label>
								<label className="item-right1">
									中国银行股份有限公司重庆冉家坝支行
								</label>
							</div>
							<div className="item1">
								<label className="item-left1">或</label>
								<label className="item-right1">
									中国银行股份有限公司重庆渝北支行
								</label>
							</div>
						</div>
					</div>
					{this.state.cardList.map((item, index) => {
						return (
							<div
								key={index}
								className={
									index == 0 ? "up-load-content" : "mt20 up-load-content"
								}
							>
								<ul className="list-content">
									<List>
										<div className="item">
											<InputItem
												placeholder="请输入还款账号"
												type="number"
												value={item.payAccount}
												onFocus={this.InputOnFocus.bind(this, index)}
												onBlur={this.InputOnBlurFocus.bind(this)}
												onChange={this.changeCallback.bind(
													this,
													"payAccount",
													index
												)}
											>
												还款账号
											</InputItem>
											{index != 0 && (
												<div
													className="input-right-div"
													onClick={this.deleteBtn.bind(this, index)}
												>
													<img
														className="input-right-img"
														src={require("../../images/icon-bank-delete.png")}
													/>
												</div>
											)}
										</div>
										<div className="item">
											<InputItem
												name="input2"
												moneyKeyboardAlign="left"
												placeholder="请输入还款金额"
												value={item.payAmt}
												maxLength={11}
												onFocus={this.InputOnFocus.bind(this, index)}
												onBlur={this.InputOnBlurFocus.bind(this)}
												onChange={this.changeCallback.bind(
													this,
													"payAmt",
													index
												)}
											>
												还款金额
											</InputItem>
											<div className="input-right-div">
												<span>元</span>
											</div>
										</div>
										<li
											id={"repayVoucherSelectImage" + index}
											className="select-img"
											onClick={this.showActionSheet.bind(this, index)}
										>
											<span className="label">上传照片</span>
											<span
												className={
													item.imageUrl == "" && !item.imageUrlCheck
														? "place-holder err-img"
														: "place-holder"
												}
											>
												{item.imageUrl == "" ? "请选择照片" : "已选择"}
											</span>
											<span
												className="thumbnail-cont"
												style={{
													display: item.imageUrl == "" ? "none" : "block"
												}}
											>
												<img src={item.showUrl != "" ? item.showUrl : ""} />
											</span>
											<i className="icon-arrorw-right"></i>
										</li>
									</List>
									<div id={"bottom" + index}></div>
								</ul>
							</div>
						);
					})}
					<a
						className="submit-btn"
						id="bottomDom"
						onClick={this.addCard.bind(this)}
					>
						+添加新的凭证
					</a>
					<a
						className="submit-btn button-2"
						id="bottomDom"
						onClick={this.postInform.bind(this)}
					>
						提交
					</a>
					<BounceSpace params={{ isShowBounce: this.state.isShowBounce }} />
				</div>
			</div>
		);
	}

	InputOnFocus = i => {
		this.setState({
			isShowBounce: true
		});
		if (i != 0) {
			let windowHeight = window.innerHeight; //屏幕高度
			let idFlag = "bottom" + i;
			let offsetTop =
				document.getElementById(idFlag).offsetTop +
				document.getElementById("header").offsetHeight; //元素距离顶部窗口的高度
			let temp1 = windowHeight - offsetTop; //元素距离底部窗口的高度
			let temp2 = (this.state.keybordHeight - temp1).toFixed(2); //>0说明键盘遮盖了输入框,需要添加一个动态高度
			if (temp2 >= 0) {
				let height = this.state.keybordHeight - 80 + "px";
				document.getElementById("bounce-space").style.height = height;
			}
			setTimeout(() => {
				document.getElementById(idFlag).scrollIntoView(true);
			}, 500);
		}
	};

	InputOnBlurFocus = () => {
		this.setState({
			isShowBounce: false
		});
	};

	//删除按钮
	deleteBtn(index) {
		let list = this.state.cardList;
		list.splice(index, 1);
		this.setState({
			cardList: list
		});
	}

	//文本框获取光标事件
	focusCallback(programs) {
		this.currentInput = programs.currentInput;
		let _cardList = this.state.cardList;
		_cardList[programs.index][programs.type + "Check"] = true;
		this.setState({
			cardList: _cardList
		});
	}

	//文本框改变事件
	changeCallback(type, index, value) {
		let _cardList = this.state.cardList;
		if (type == "payAmt") {
			//还款金额
			_cardList[index].payAmt = value;
			this.setState({
				cardList: _cardList
			});
			return false;
		} else if (type == "payAccount") {
			//还款账号
			_cardList[index].payAccount = value;
		} else {
			_cardList[index][type] = value;
		}
		this.setState({
			cardList: _cardList
		});
	}

	//添加凭证按钮
	addCard() {
		if (this.state.cardList.length < 3) {
			let arr = this.state.cardList;
			arr.push({
				payAccount: "", //付款账号
				payAmt: "", //付款金额
				imageUrl: "" //上传图片地址
			});
			this.setState({
				cardList: arr
			});
		} else {
			Toast.info("最多上传3组凭证信息", 2);
		}
	}

	//提交按钮
	postInform() {
		if (!this.checkAllInput()) {
			return false;
		}
		if (this.state.hasUpload) {
			return false;
		}
		this.uploadImage();
	}

	//校验所有表单字段
	checkAllInput() {
		let inputList = this.state.cardList;
		let flag = true;
		for (let i = 0; i < inputList.length; i++) {
			let payAccountParams = inputList[i].payAccount.replace(/\s/g, "");
			if (!payAccountParams) {
				Toast.info("存在未填写的还款账号", 2);
				return false;
			} else if (!checkTool.isBankNo({ valueParams: "" + payAccountParams })) {
				Toast.info("还款账号格式有误", 2);
				return false;
			}
			if (!inputList[i].payAmt) {
				Toast.info("存在未填写的还款金额", 2);
				return false;
			} else if (
				!checkTool.isMoney({ valueParams: "" + inputList[i].payAmt })
			) {
				Toast.info("还款金额格式有误", 2);
				return false;
			}
			if (!inputList[i].imageUrl) {
				Toast.info("存在未上传的照片", 2);
				return false;
			}
		}
		return flag;
	}

	//点击“上传照片”
	showActionSheet = index => {
		let _that = this;
		const BUTTONS = ["拍照", "相册", "取消"];
		ActionSheet.showActionSheetWithOptions(
			{
				options: BUTTONS,
				cancelButtonIndex: BUTTONS.length - 1,
				maskClosable: true,
				"data-seed": "logId",
				wrapProps
			},
			i => {
				if (i == 0) {
					_that.selectImage(1, index);
				} else if (i == 1) {
					_that.selectImage(2, index);
				} else if (i == 2) {
					// Toast.info("取消",2);
				}
			}
		);
	};

	//点击请选择图片
	selectImage(type, index) {
		let imagePicker = {
			type: "" + type, //图片选择类型
			imageName:
				this.props.getAppPlatformsDatas.userToken +
				"_16_" +
				(index + 1) +
				".JPEG",
			imageSize: 100 * 1024, //图片大小 （0 表示不压缩，100*1024 表示 100Kb）
			thumbnailSize: 4 * 1024 //缩略图大小（0表示不压缩，不建议, 10*1024 表示 100Kb）
		};
		let _that = this;
		yhTools.chooseImage(imagePicker).then(
			res => {
				if (res.status == "1000") {
					let _cardList = _that.state.cardList;
					_cardList[index]["imageUrl"] = res.data.path;
					_cardList[index]["showUrl"] = res.data.base64;
					_that.setState({
						cardList: _cardList
					});
				} else if (res.status == "3001") {
					let str = "";
					if (index == 1) {
						str = "您需要允许永辉金融访问相机权限才能拍照";
					} else {
						str = "您需要允许永辉金融访问相册权限才能上传照片";
					}
					antnAlert("", str, [
						{
							text: "取消",
							onPress: () => {}
						},
						{
							text: "去设置",
							onPress: () => {
								_that.alertOK();
							}
						}
					]);
				}
			},
			() => {}
		);
	}

	//弹窗确定按钮
	alertOK() {
		//打开设置页面
		window.YHAuthorize.callHandler("Device_Setting", "", () => {});
	}

	//上传图片
	uploadImage() {
		let imageDataList = [];
		let cardList = this.state.cardList;
		cardList.map((item, index) => {
			let payAccountParams = item.payAccount.replace(/\s/g, "");
			imageDataList.push({
				name:
					this.props.getAppPlatformsDatas.userToken +
					"_16_" +
					(index + 1) +
					".JPEG",
				path: item.imageUrl,
				params: {
					params: JSON.stringify({
						cino: this.props.loanProcessDataReducer.cino, //借据号
						lnPlanSeq: this.props.loanProcessDataReducer.lnPlanSeq, //期供编号
						name: "upload" + index + ".jpeg", //文件名
						payAmounts: item.payAmt, //付款金额
						payAccounts: payAccountParams, //付款账号
						imgIndex: index + 1, //图片序号,1,2,3
						planperi: this.props.loanProcessDataReducer.planperi //期供号
					})
				}
			});
		});
		let _that = this;
		this.setState({
			hasUpload: true
		});
		Toast.loading("正在提交中...", 100, () => {});

		let header = this.props.getAppPlatformsDatas;
		header.onceToken = this.state.onceToken;
		const params = {
			url: "/file/upload/1",
			header: header,
			imageArray: imageDataList,
			params: {},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			Toast.hide();
			// Toast.info("图片上传完毕",2);
			if (res.code == "0") {
				_that.upLoadFormData();
			} else {
				Toast.info(res.message, 2);
				_that.setState({
					hasUpload: false
				});
			}
		});
	}

	//上传完凭证图片后上传表单数据
	upLoadFormData = () => {
		const params = {
			url: `/loan/commitImgEnd/0`,
			header: this.props.getAppPlatformsDatas,
			params: {
				cino: this.props.loanProcessDataReducer.cino, //借据编号
				lnPlanSeq: this.props.loanProcessDataReducer.lnPlanSeq, //期供编号
				planperi: this.props.loanProcessDataReducer.planperi
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			if (res.code == "0") {
				window.location.replace("#/bankTransferMoneySuccess"); //成功之后跳转到成功页
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_setDialog: options => {
			dispatch(setDialog(options));
		}
	};
}

const BankTransferMoneyPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(BankTransferMoney);
export default BankTransferMoneyPage;
